<template>
    <el-dialog v-if="makeVisible" :visible.sync="makeVisible" :fullscreen="true" :before-close="handleClose"
        :modal-append-to-body="false" v-loading="loading">
        <div class="makepage" v-if="course_id || unit_id">
            <el-row>
                <div class="upload">
                    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                        <el-form-item label="内容:">
                            <div class="upload__title">
                                <div class="upload__title-content">
                                    <el-button type="primary" @click="handleUploadStatus">请选择图片，MP3音频文件</el-button>
                                    <div class="upload__title-content-tip"><span>*</span>
                                        （必填）图片使用JPG或PNG文件，推荐：1024*768。音频使用不超过50M的MP3格式文件。</div>
                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item prop="content_list" ref="content_list">

                            <div class="upload__first">
                                <el-row class="upload__first-title">
                                    <span>第一步: 上传相应的素材文件。</span>
                                </el-row>

                                <el-row class="upload__first-content" :gutter="30">

                                    <el-col :span="14">
                                        <el-table :data="form.content_list" border style="width: 100%" row-key="id"
                                            :header-cell-style="{ background: '#81D3F8', color: '#0000FF' }">
                                            <el-table-column prop="title" align="center" label="图片">
                                            </el-table-column>
                                            <el-table-column prop="isEdit" align="center" width="90" sortable
                                                label="状态">
                                                <template slot-scope="scope">

                                                    <div>
                                                        {{ scope.row.hasEdit ? '已编辑' : '未编辑' }}
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" width="260" label="操作">
                                                <template slot-scope="scope">

                                                    <PersButton type="primary" perms="kanke:textbook:courseware:edit"
                                                        label="编辑点读"
                                                        @click="handleEditPoint(scope.row, scope.$index)" />

                                                    <PersButton type="danger" perms="kanke:textbook:courseware:del"
                                                        label="删除" @click="handleDel(scope.$index, 'img')" />
                                                    <PersButton type="warning" perms="kanke:textbook:courseware:edit"
                                                        label="替换图片"
                                                        @click="handleReplaceImg(scope.row, scope.$index)" />
                                                </template>
                                            </el-table-column>
                                        </el-table>

                                    </el-col>

                                    <el-col :span="10">
                                        <el-table :data="form.audio_list" row-key="id" key="1"
                                            :header-cell-style="{ background: '#81D3F8', color: '#0000FF' }" border
                                            style="width: 100%">
                                            <el-table-column prop="title" align="center" label="音频">
                                            </el-table-column>
                                            <el-table-column align="center" width="90" label="操作">
                                                <template slot-scope="scope">
                                                    <PersButton type="danger" perms="kanke:textbook:courseware:del"
                                                        label="删除" @click="handleDel(scope.$index, 'audio')" />
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-form-item>
                        <el-form-item>

                            <div class="upload__second">
                                <div class="upload__second-title">
                                    <span>第二步: 匹配翻页时间点。</span>
                                </div>
                                <div class="upload__second-content">
                                    <swiper class="upload__second-content-item" ref="mySwiper" :options="swiperOption">
                                        <swiper-slide v-for="(item, index) in form.content_list" :key="index">
                                            <div class="upload__second-content-item-img">
                                                <img :src="item.url" />
                                                <p class="upload__second-content-item-img-tip">
                                                    <span>{{ index + 1 }}</span>/{{ form.content_list.length }}
                                                </p>
                                            </div>

                                            <img v-if="!isPlay && form.audio_list.length"
                                                class="upload__second-content-item-btn" @click="handlePlayAudio"
                                                src="@/assets/img/kanke/material/btn_play.png" alt="">
                                        </swiper-slide>
                                        <div class="swiper-button-prev" slot="button-prev">
                                            <span>设置上个翻页时间点</span>
                                        </div>
                                        <div class="swiper-button-next" slot="button-next">
                                            <span>设置下个翻页时间点</span>
                                        </div>
                                    </swiper>
                                </div>
                                <div v-if="form.audio_list.length" class="upload__second-bottom">
                                    <audio :src="form.audio_list[0].url" ref="myAudio" controls="controls"></audio>
                                    <el-button type="primary" @click="handleResetAudio">重置翻页时间点</el-button>
                                    <el-button type="primary" @click="handlePreview">预览翻页效果</el-button>
                                </div>
                                <div class="upload__second-pageinfo">
                                    <div class="upload__second-pageinfo-title">翻页时间点</div>
                                    <div class="upload__second-pageinfo-content"><span
                                            v-for="(item, index) in form.turn_point" :key="index"
                                            @click="handleEditTurnPoint(item, index)">{{
                                                convertToTimeFormat(item) }}</span>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item prop="read_type" ref="read_type">
                            <el-radio-group v-model="form.read_type">
                                <el-radio :label="1">（朗读类型）课文的音频是朗读类型，一页一页地朗读图片的内容。APP上播放在翻页时停顿1.5秒，使翻页更流畅。</el-radio>
                                <el-radio :label="2">（音乐类型）课文的音频是音乐或歌曲，或有背景音乐。需要连续播放。APP播放翻页时音频不会停顿，连续播放音频。</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="备注:" prop="remark">
                            <el-input type="textarea" v-model="form.remark" maxlength="255"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">保存</el-button>
                        </el-form-item>
                    </el-form>

                </div>

            </el-row>
            <MakePoint v-if="dialogVisible" :dialogVisible.sync="dialogVisible" :currentIndex="currentIndex"
                :currentItem="currentItem" :audioList="form.audio_list" @confirm="handleConfirmPoint"
                :prevTurnPoint="prevTurnPoint" @closeModal="closeModal" :currentTurnPoint="currentTurnPoint" />
            <upload-file v-if="uploadDialogVisible" :visible.sync="uploadDialogVisible" @childFileEvent="onFinish"
                :showTab="showTab" :limitNum="limitNum" :limitType="limitType" :type="type" />

        </div>
        <el-empty v-else description="参数错误!">

        </el-empty>
    </el-dialog>
</template>
<script>
import { mapActions, mapState } from 'vuex';

import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
import MakePoint from './MakePoint.vue';
import { convertToTimeFormat } from '@/utils/index'
import UploadFile from '@/views/kanke/components/UploadFile.vue'

export default {
    name: "KanKeTextbookCourseWareMakePage",
    props: {
        makeVisible: {
            type: Boolean,
        },
        unit_id: {
            type: [String, Number],

        },
        course_id: {
            type: [String, Number]
        },
        editId: {
            type: [String, Number]
        },
        handleFinish: {
            type: Function
        }
    },
    components: {
        Swiper,
        SwiperSlide,
        MakePoint,
        UploadFile
    },
    data() {
        return {
            // 1: '文档', 2: '视频',  3: '音频',   4: '图片'
            type: 'all',
            limitType: [3, 4],// 限制文件类型 
            limitNum: 10,
            showTab: ['all', 'image', 'doc', 'video', 'audio'],
            dialogVisible: false,
            currentItem: {},
            currentIndex: -1,
            currentTurnPoint: 0,
            prevTurnPoint: 0,
            uploadDialogVisible: false,
            form: {
                content_list: [
                ],
                audio_list: [],
                turn_point: [],
                read_type: '',
                remark: '',
            },
            swiperOption: {
                notNextTick: true,
                preventClicks: true,
                disableOnInteraction: true,
                spaceBetween: 30,
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                    disabledClass: 'swiper-button-disabled'
                },
                on: {
                    slidePrevTransitionStart: () => {
                        this.handlePrev(this.swiper)
                    },
                    slideNextTransitionStart: () => {
                        this.handleNext(this.swiper)
                    }
                },
            },
            isPlay: false,
            rules: {

                read_type: [
                    { required: true, message: '请选择朗读类型', trigger: 'change' }
                ],
                content_list: [
                    { required: true, message: '请上传图片', trigger: 'change' }
                ],
                remark: [
                    { min: 1, max: 255, message: '长度在 1 到 255 个字', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        ...mapState('courseware', ['contentDetail', 'loading']),

        swiper() {
            return this.$refs.mySwiper.$swiper
        },
    },
    watch: {
        editId: {
            handler(newVal) {
                if (newVal) {
                    this.getContentDetail({ id: newVal })
                } else {
                    this.$store.commit('courseware/setContentDetail', {})
                }
            },
            immediate: true
        },
        contentDetail: {
            handler(newVal) {
                if (newVal) {
                    this.form = { ...newVal }
                }
            }
        }
    },
    methods: {
        ...mapActions('courseware', ['addContent', 'getContentDetail', 'updateContent']),
        handleReplaceImg(item, index) {
            this.uploadDialogVisible = true
            this.limitType = [4]
            this.limitNum = 1
            this.showTab = ['image']
            this.type = 'image'
            this.currentItem = { ...item }
            this.currentIndex = index
        },
        handleEditTurnPoint(item, index) {
            this.$prompt('请输入新翻页时间', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue: item,
                inputType: 'number',
                inputErrorMessage: '内容不合法,仅支持数字'
            }).then(({ value }) => {
                if (index) {
                    // 不能比前一个小
                    if (Number(this.form.turn_point[index - 1]) > Number(value)) {
                        this.$message.error('翻页时间不能比前一页小')
                        return
                    }
                    // 不能比后一个大 判断是不是最后一个
                    if (this.form.turn_point == index + 1) {
                        // 判断是否比总时长大
                        if (Number9this.form.audio_list[0].duration < Number(value)) {
                            this.$message.error('翻页时间不能比音频总时长大')
                            return
                        }
                    }
                    if (this.form.turn_point[index + 1]) {
                        if (Number(this.form.turn_point[index + 1]) < Number(value)) {
                            this.$message.error('翻页时间不能比后一页大')
                            return
                        }
                    }
                }
                this.form.turn_point.splice(index, 1, value)
            })
        },
        handleClose() {
            this.$emit('update:makeVisible', false)
        },
        convertToTimeFormat,
        handleUploadStatus() {
            this.uploadDialogVisible = true
        },
        onFinish(val, allMultipleVal) {
            //     url: 'http://res.iiiview.net/ugc/file/2024/7/31/7daf6226cc1744ac95ab24d7a862af6f.jpg?x-oss-process=image/auto-orient,1',
            //     title: '图片1',
            //     id: 1,
            //     pointList: [],
            //     type: 1,
            //     hasEdit: false,
            if (!allMultipleVal || allMultipleVal.length == 0) {
                this.$message.error('请选择文件')
                return
            }
            if (this.type == 'image') {
                // 替换图片
                this.currentItem.url = allMultipleVal[0].file_url
                this.currentItem.title = allMultipleVal[0].title
                this.form.content_list.splice(this.currentIndex, 1, this.currentItem)
                this.limitType = [3, 4]
                this.limitNum = 10
                this.showTab = ['all', 'image', 'doc', 'video', 'audio']
                this.type = 'all'
                this.currentItem = {}
                this.currentIndex = -1
                return
            }
            let content_list = [];
            let audio_list = [];

            allMultipleVal.map(item => {
                let newItem = {
                    url: item.file_url,
                    id: item.id,
                    title: item.title,
                    type: item.type,
                    pointList: [],
                    hasEdit: false,
                }
                if (item.type == 4) {
                    content_list.push(newItem)

                }
                if (item.type == 3) {
                    // audio_list 只保存一个, 再增加的只是替换掉第一个
                    audio_list.splice(0, 1, newItem)
                }
            })
            if (content_list.length) {
                this.form.content_list = this.form.content_list.concat(content_list)
                this.$refs.content_list.onFieldChange()
            }
            if (audio_list.length) {
                this.form.audio_list.splice(0, 1, audio_list[0])
            }

        },
        handleConfirmPoint(data, index) {
            if (index >= 0) {
                this.form.content_list.splice(index, 1, data)
                this.dialogVisible = false
            }
        },
        handleEditPoint(item, index) {
            // 检查是否上传音频
            if (this.form.audio_list.length == 0) {
                this.$confirm(
                    '没有设置音频，请先设置音频', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                })
                return false;
            }
            if (this.form.content_list.length != this.form.turn_point.length && this.form.content_list.length > 1) {
                this.$confirm(
                    '翻页时间点个数和图片不相等，请重新设置翻页时间点！', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                })
                return false;
            }
            if (this.form.audio_list.length == 0) {

                this.$confirm(
                    '没有设置音频，请先设置音频', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                })
                return false;
            }
            if (this.form.turn_point.length == 0) {
                this.$confirm(
                    '没有设置翻页时间！请点“中间的播放按钮和设置下一个翻页时间点按钮”设置翻页时间', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                })
                return false;
            }
            if (!this.checkTimeLineValue()) {
                return false;
            }
            this.currentItem = item
            this.currentIndex = index
            this.prevTurnPoint = index == 0 ? 0 : this.form.turn_point[index - 1]
            this.currentTurnPoint = this.form.turn_point[index]
            this.dialogVisible = true;
        },
        closeModal() {
            this.currentItem = {}
            this.currentIndex = -1
            this.currentTurnPoint = 0
        },
        handlePlayAudio() {
            this.isPlay = true
            this.$refs.myAudio.play();
        },
        handlePrev(swiper) {
            const curTime = this.$refs.myAudio.currentTime;
            let duration = this.$refs.myAudio.duration;
            if (Number(curTime) == 0 || duration == "NaN") {
                return false;
            }
            if (swiper.activeIndex == 0) {
                this.$refs.myAudio.currentTime = 0;
                this.form.turn_point = []
            } else {
                // 记录当前播放器时间
                this.form.turn_point = this.form.turn_point.splice(0, swiper.activeIndex);

                this.$refs.myAudio.currentTime = this.form.turn_point[swiper.activeIndex - 1];
            }

        },
        handleNext(swiper) {
            // 记录当前播放器时间
            let curTime = this.$refs.myAudio.currentTime;
            let duration = this.$refs.myAudio.duration;
            if (Number(curTime) == 0 || duration == "NaN") {
                return false;
            }
            // 格式化 curTime 保留三位小数
            curTime = Number(curTime).toFixed(3);
            if (this.form.turn_point.length < swiper.slides.length && this.form.turn_point.length < swiper.activeIndex) {
                if (swiper.activeIndex == this.form.turn_point.length - 1) {
                    // 替换 turn_point 的最后一个元素
                    this.form.turn_point.splice(this.form.turn_point.length - 1, 1, curTime);
                } else {
                    this.form.turn_point.push(curTime);

                }
                if (swiper.isEnd) {
                    this.form.turn_point.push(duration);
                    this.$message.warning("最后一个翻页时间点（音频时长）已自动加上。设置完成！");
                }
            }


        },
        handlePreview() {
            if (!this.$refs.myAudio) return
            this.$refs.myAudio.pause();
            this.$refs.myAudio.play();
            this.$refs.myAudio.currentTime = 0;

            this.isPlay = true;
            if (this.previewTimer) {
                clearInterval(this.previewTimer)
            }
            const turn_point = [...this.form.turn_point]
            this.previewTimer = setInterval(() => {
                if (!this.$refs.myAudio) {
                    clearInterval(this.previewTimer)
                    return;
                }
                const curTime = this.$refs.myAudio.currentTime
                //control slide
                for (var i = 0; i < turn_point.length; i++) {
                    if (curTime < Number(turn_point[0])) {
                        if (this.swiper.activeIndex != 0) {
                            this.swiper.slideTo(0, 1000, false)
                        }
                    } else if (
                        i + 1 < turn_point.length &&
                        curTime > Number(turn_point[i]) &&
                        curTime < Number(turn_point[i + 1])
                    ) {
                        if (this.swiper.activeIndex != Number(i + 1)) {
                            this.swiper.slideTo(Number(i + 1), 1000, false)
                        }
                    }
                    if (this.swiper.isEnd) {
                        clearInterval(this.previewTimer)
                    }
                }
            }, 250)
        },
        handleResetAudio() {
            this.$refs.myAudio.currentTime = 0;
            this.$refs.myAudio.pause();
            this.isPlay = false;
            this.swiper.slideTo(0, 1000, false);
            this.form.turn_point = [];
        },

        onSubmit() {
            if (this.form.audio_list.length && this.form.content_list.length != this.form.turn_point.length && this.form.content_list.length > 1) {
                this.$confirm(
                    '翻页时间点个数和图片不相等，请重新设置翻页时间点！', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                })
                return false;
            }
            this.$refs['form'].validate((valid) => {
                if (!valid) return false
                const params = {
                    course_id: this.course_id,
                    ...this.form,
                }
                const api = this.editId ? this.updateContent : this.addContent
                api(params).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                        this.$emit('handleFinish', false)
                    }
                })
            })

        },
        handleDel(index, type) {
            // 删除内容
            if (type == 'img') {
                this.form.content_list.splice(index, 1)
            }
            if (type === 'audio') {
                this.form.audio_list.splice(index, 1)
                // 删除 翻页时间点
                this.form.turn_point = []
            }

        },
        checkTimeLineValue() {
            for (let i = 0; i < this.form.turn_point.length; i++) {
                let timeItem = this.form.turn_point[i]
                if (
                    timeItem == 0 ||
                    'undefined' == timeItem ||
                    '0' == timeItem ||
                    'nan' == timeItem.toString().toLowerCase() ||
                    isNaN(timeItem)
                ) {
                    this.$message.error(

                        '第' +
                        (i + 1) +
                        '个时间点不正常！值为：' +
                        timeItem +
                        ',请重新设置翻页时间！'
                    )
                    return false
                }

                let tempval = 0
                if (i > 0) {
                    tempval = this.form.turn_point[i - 1]
                }

                if (Number(timeItem) - Number(tempval) <= 0) {
                    this.$message.error(
                        '第' +
                        (i + 1) +
                        '个时间点不正常！小于前一个时间点！请重新设置翻页时间！'
                    )
                    return false
                }
            }
            return true
        }

    },
    onBeforeUnmount() {
        clearInterval(this.previewTimer)
    }
}
</script>
<style lang="scss" scoped>
.makepage {
    padding: 20px;
    min-width: 1280px;

    .upload {

        &__title {
            margin-bottom: 20px;
            margin-bottom: 20px;

            &-content-tip {
                margin-top: 10px;

                font-size: 12px;
                color: #999;

                span {
                    color: red;
                }
            }
        }

        &__first {

            &-title {
                margin: 10px 0;
            }

            &-content {
                border: 1px solid #ccc;
                padding: 10px;
                border-radius: 5px;
            }
        }

        &__second {
            margin-top: 30px;

            &-title {
                margin: 10px 0;
            }

            &-content {
                border: 1px solid #ccc;
                border-radius: 5px;
                position: relative;

                &-item {

                    &-img {
                        width: 55%;
                        height: 771px;
                        margin: 0 auto;
                        // 居中显示
                        display: flex;
                        justify-content: center;
                        align-items: center;

                        img {
                            width: auto;
                            height: 100%;
                            margin: 0 auto;

                        }
                    }

                    &-img-tip {
                        position: absolute;
                        bottom: 10px;
                        left: 50%;
                        transform: translateX(-50%);
                        color: #000;
                        font-size: 16px;
                    }

                    &-btn {
                        position: absolute;
                        bottom: 40%;
                        left: 50%;
                        transform: translateX(-50%);
                        cursor: pointer;
                    }

                    .swiper-button-disabled {
                        color: gray;
                    }
                }
            }

            &-bottom {
                margin: 20px 0;
                display: flex;
                align-items: center;
                justify-content: flex-start;

                audio {
                    width: 66%;
                }

                :nth-child(2) {
                    margin: 0 20px;
                }
            }

            &-pageinfo {
                &-title {
                    margin-bottom: 10px;
                    ;
                }

                &-content {
                    display: flex;
                    flex-wrap: wrap;
                    align-items: center;
                    justify-content: flex-start;

                    span {
                        margin-right: 10px;
                        border: 1px solid #ccc;
                        padding: 0 5px;
                    }
                }
            }
        }

        .el-radio-group {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;

            .el-radio {
                margin: 10px 0;
            }
        }

        ::v-deep .el-form-item__label {
            font-weight: bold;
            font-size: 20px;
        }

        // 我想清除 swiper 翻页的 箭头
        .swiper-button-next:after,
        .swiper-button-prev:after {
            display: none;
        }

    }
}
</style>